layui.use(['table','form', 'element'], function () {
    let table = layui.table,
        form = layui.form,
        $ = layui.jquery,
       element = layui.element;

    //方法级渲染
    table.render({
        elem: '#deploy'
        , url: '/deploy/list'
        , toolbar: '#toolbarTable'
        , title: '自动部署配置'
        , totalRow: true
        ,skin: 'line'
        , where: {
            type: 0,
            content: $('#content').val(),
            serverId: $('#serverId').val(),
        }
        , id: "deploy"
        , cols: [[
            {checkbox: true, fixed: true}
            , {field: 'projectName', title: '项目名称', width: 150, sort: true}
            , {field: 'moduleName', title: '模块名称', width: 250, sort: true}
            , {field: 'namespaceName', title: '命名空间', width: 120, sort: true}
            , {field: 'ip', title: '宿主机ip', width: 140, sort: true}
            , {field: 'lastDeployDate', title: '最近部署时间', width: 160, sort: true}
            , {field: 'commandStart', title: '启动命令', width: 150, sort: true}
            , {field: 'lastStatus', title: '部署状态', width: 350, sort: true,templet: function (d) {
                    //部署状态：0空闲 1编译中 2编译失败 3编译成功 4代码上传  5启动失败 6启动成功
                    let progressBar = 0;
                    let ys = '';
                    let statusName = '';
                    if (d.lastStatus == 0) {
                        ys='layui-btn-primary'
                        progressBar = 0;
                        statusName = '<span class="layui-badge  layui-bg-gray" style="float:left;">空闲</span>';
                    }
                    if (d.lastStatus == 1) {
                        ys='layui-btn-normal'
                        progressBar = 30;
                        statusName = '<span class="layui-badge  layui-bg-blue" style="float:left;">编译中</span>';
                    }
                    if (d.lastStatus == 2) {
                        ys='layui-btn-danger'
                        progressBar = 40;
                        statusName = '<span class="layui-badge  layui-bg-warm" style="float:left;">编译失败</span>';
                    }
                    if (d.lastStatus == 3) {
                        ys='layui-btn-normal'
                        progressBar = 50;
                        statusName = '<span class="layui-badge  layui-bg-blue" style="float:left;">编译成功</span>';
                    }
                    if (d.lastStatus == 4) {
                        ys='layui-btn-normal'
                        progressBar = 70;
                        statusName = '<span class="layui-badge  layui-bg-blue" style="float:left;">代码上传中</span>';
                    }
                    if (d.lastStatus == 5) {
                        ys='layui-btn-danger'
                        progressBar = 80;
                        statusName = '<span class="layui-badge  layui-bg-warm" style="float:left;">启动失败</span>';
                    }
                    if (d.lastStatus == 6) {
                        ys='layui-btn-orange'
                        progressBar = 100;
                        statusName = '<span class="layui-badge  layui-bg-green" style="float:left;">启动成功</span>';
                    }

                    //***重点***：拼接进度条
                    return '<div style="display:inline"><div style="float:left;width: 200px" class="layui-progress layui-progress-big" lay-showpercent="true">' +
                        '<div class="layui-progress-bar '+ys+'" lay-percent="'+progressBar+'%">' +
                        '</div>' +
                        '</div>'+statusName+'' +
                        '</div>'

                }}
            , {fixed: 'right', title: '操作', toolbar: '#barDemo', width: 300}
        ]]
        , even: true
        , page: true //是否显示分页
        , skip: true //开启跳页
        , limits: [10, 30, 60]
        , width: 1700
        // , height: 'full-150'
        , limit: 10 //每页默认显示的数量
        , parseData: function (res) { //res 即为原始返回的数据
            var data = res.data;
            return {
                "code": status, //解析接口状态   （好像必须是0 才可以）
                "msg": data.desc, //解析提示文本
                "count": data.total, //解析数据长度
                "data": data.records //解析数据列表
            };
        }
        ,done:function (res,currentCount) {
            //***重点***：table渲染完成后渲染element进度条
            element.render()
        }

    });


    //头工具栏事件
    table.on('toolbar(deploy)', function (obj) {
        let data = table.checkStatus(obj.config.id).data;
        switch (obj.event) {
            case 'add':
                add();
                break;
            case 'deploySelect':
                deploySelect(data);
                break;
            case 'restartService':
                restartService(data);
                break;
            case 'stopService':
                stopService(data);
                break;
            case 'allLog':
                allLog();
                break;
        }
        ;
    });

    //监听行工具事件
    table.on('tool(deploy)', function (obj) {
        const data = obj.data;
        if (obj.event === 'update'){
            update(data);
        }else if (obj.event === 'del'){
            del(data.id)
        }else if (obj.event === 'log'){
            log(data)
        }else if (obj.event === 'ssh'){
            ssh(data)
        }
    });

    function deploySelect(data) {
        if (data.length==0){
            layer.msg("请先勾选数据",{icon:2,time:3000});
            return;
        }
        let ids = "";
        for (let i = 0; i < data.length; i++) {
            ids+=data[i].id+","
        }
        ids = ids.substr(0,ids.length-1);
        $.ajax({
            type: "post",//方法类型
            dataType: "json",//预期服务器返回的数据类型
            url: "/deploy/deploySelect",//url
            data:{ids:ids},
            success: function (result) {
            },
            error: function () {
                alert("异常！");
            }
        });

    }
    function restartService(data) {
        if (data.length===0){
            layer.msg("请先勾选数据",{icon:2,time:3000});
            return;
        }
        let ids = "";
        for (let i = 0; i < data.length; i++) {
            ids+=data[i].id+","
        }
        ids = ids.substr(0,ids.length-1);
        $.ajax({
            type: "post",//方法类型
            dataType: "json",//预期服务器返回的数据类型
            url: "/deploy/restartService",//url
            data:{ids:ids},
            success: function (result) {
                localStorage.setItem("status","ON");
                if (result.code == 0) {
                    layer.msg(result.data,{icon:1,time:1000},function () {
                        location.reload();
                    });
                }
            },
            error: function () {
                alert("异常！");
            }
        });

    }
    function stopService(data) {
        if (data.length===0){
            layer.msg("请先勾选数据",{icon:2,time:3000});
            return;
        }
        var ids = "";
        for (var i = 0; i < data.length; i++) {
            ids+=data[i].id+","
        }
        ids = ids.substr(0,ids.length-1);
        $.ajax({
            type: "post",//方法类型
            dataType: "json",//预期服务器返回的数据类型
            url: "/deploy/stopService",//url
            data:{ids:ids},
            success: function (result) {
                if (result.code == 0) {
                    layer.msg(result.data,{icon:1,time:1000},function () {
                        location.reload();
                    });
                }
            },
            error: function () {
                alert("异常！");
            }
        });

    }
    function del(id) {
        layer.confirm("确认要删除吗，删除后不能恢复", { title: "删除确认" }, function (index) {
            $.ajax({
                type: "post",//方法类型
                dataType: "json",//预期服务器返回的数据类型
                url: "/deploy/deleteDeploy",//url
                data:{id:id},
                success: function (result) {
                    if (result.code == 0) {
                        layer.msg(result.data,{icon:1,time:3000},function () {
                            location.reload();
                        });
                    };
                },
                error: function () {
                    alert("异常！");
                }
            });
        })
    }

    function add() {
        layer.open({
            type: 2,
            title: '新增配置',
            area: ['1000px', '700px'],
            fix: false, //
            closeBtn: false,
            shift: 2,
            shadeClose: true,
            content: ["deployAdd.html", 'no'],
            success: function (layero, index) {
                form.render();
            },
            yes: function () {
            }
        });
    }
    let dropData
    function update(data) {
        layer.open({
            type: 2,
            title: '修改配置',
            area: ['1000px', '700px'],
            fix: false, //
            closeBtn: false,
            shift: 2,
            shadeClose: true,
            content: ["deployUpdate.html", 'no'],
            success: function (layero, index) {
                const body = layer.getChildFrame('body', index);//获取弹出层的dom元素
                const iframeWin = layero.find('iframe')[0].contentWindow;
                body.find("#id").val(data.id);
                body.find("#projectName").val(data.projectName);
                body.find("#projectId").val(data.projectId);
                body.find("#namespaceName").val(data.namespaceName);
                body.find("#namespaceId").val(data.namespaceId);
                body.find("#moduleName").val(data.moduleName);
                body.find("#serverId").val(data.serverId);
                body.find("#ip").val(data.ip);
                body.find("#userName").val(data.userName);
                body.find("#password").val(data.password);
                body.find("#commandKill").val(data.commandKill);
                body.find("#commandDelete").val(data.commandDelete);
                body.find("#localFile").val(data.localFile);
                body.find("#remoteTargetDirectory").val(data.remoteTargetDirectory);
                body.find("#commandStart").val(data.commandStart);
                body.find("#starTime").val(data.starTime);
                body.find("#commandLineCount").val(data.commandLineCount);
                body.find("#maven").val(data.maven);
                body.find("#serverId").val(data.serverId);
                if (data.build==1) {
                    body.find("#build1").attr("checked", true);
                }else {
                    body.find("#build2").attr("checked", true);
                }

                let value= data.serverId
                let selectObj=dropData.filter(item=>{
                    return item.id==value
                })
                body.find("#groupName").val(selectObj[0].ip);
                iframeWin.layui.form.render();

            },
            yes: function () {
            }
        });
    }
    $(function() {
        getServer("")
        getNamespace("")
        getProject("")
        form.render('select');
    })

    function getServer(ip) {
        $.ajax({
            type: "GET",//方法类型
            dataType: "json",//预期服务器返回的数据类型
            url: "/server/getAllServer?ip="+ip,//url
            success: function (result) {
                dropData = result
                $("#serverId").html("");
                var html = "";
                $("#serverId").html("<option value=\"\">请选择服务器</option>");
                if (result != null) {
                    $.each(result, function (index, item) {
                        html += "<option  value='" + item.id + "'>" + item.ip + "</option>";
                    })
                }
                $("#serverId").append(html);
                form.render('select');
                if (ip != null && ip !=''){
                    $(".layui-form-select").addClass("layui-form-selected")
                }
            },
            error: function () {
                alert("异常！");
            }
        });
    }
    function log(data) {
        layer.open({
            type: 2,
            title: '部署详情',
            area: ['1000px', '650px'],
            fix: false, //
            closeBtn: false,
            shift: 2,
            shadeClose: true,
            content: ["log.html"],
            success: function (layero, index) {
                const body = layer.getChildFrame('body', index);//获取弹出层的dom元素
                const iframeWin = layero.find('iframe')[0].contentWindow;
                body.find("#id").val(data.id);
                body.find("#projectName").html(data.projectName);
                body.find("#ip").html(data.ip);
                iframeWin.layui.form.render();
            },
            yes: function () {
            }
        });
    }
    function ssh(data) {
        let params = {
            "ip": data.ip,
            "username": data.username,
            "password": data.password,
            "port": data.port
        };
        window["sshParams"] = params;
        const newWindow = window.open("../ssh/webssh.html");
        const loop = setInterval(function () {
            if (newWindow.closed) {
                clearInterval(loop);
            } else {
                newWindow.document.title = data.ip;
            }
        }, 1000);
    }
    function allLog() {
        layer.open({
            type: 2,
            title: '部署总概览',
            area: ['1650px', '650px'],
            fix: false, //
            closeBtn: false,
            shift: 2,
            shadeClose: true,
            content: ["allLog.html"],
            success: function (layero, index) {

            },
            yes: function () {
            }
        });
    }

    $('#query').click(function(){
        search();
    });
    $(document).keyup(function(event){
        if(event.keyCode ==13){
            search();
        }
    });
    function search(){
        //执行重载
        table.reloadData('deploy', {
            method: 'get',
            page: {
                curr: 1 //重新从第 1 页开始
            }
            , where: {
                type: 0,
                content: $('#content').val(),
                serverId: $('#serverId').val(),
                projectId: $('#projectId').val(),
                namespaceId: $('#namespaceId').val(),
            }
        }, 'data');
    }

    // $('.demoTable .layui-btn').on('click', function () {
    //     var type = $(this).data('type');
    //     active[type] ? active[type].call(this) : '';
    // });
    $('#info').on('click', function () {
         // alert("跳转日志");
    });


    //websocket对象
    let websocket = null;
    //判断当前浏览器是否支持WebSocket
    if ('WebSocket' in window) {
        websocket = new WebSocket("ws://" + sessionStorage.getItem('hostName') + "/websocket/logging");
    } else {
        console.error("不支持WebSocket");
    }

    //连接发生错误的回调方法
    websocket.onerror = function (e) {
        console.error("WebSocket连接发生错误",e);
    };
    //连接成功建立的回调方法
    websocket.onopen = function () {
        console.log("WebSocket连接成功")
    };
    //接收到消息的回调方法
    websocket.onmessage = function (event) {
        //追加
        if (event.data) {
            let data = $.parseJSON(event.data);
            if (data.table == "deploy") {
                if (data.type == 1){
                    search();
                }else if (data.type == 2){
                    layer.msg(data.data,{icon:1,time:1000},function () {
                        search();
                    });
                }else if (data.type == 3){
                    layer.msg(data.data,{icon:2,time:1000},function () {
                        search();
                    });
                }
            }
        }
    };
    //连接关闭的回调方法
    websocket.onclose = function () {
        console.log("WebSocket连接关闭")
    };


    nameInput = function(e){
        const val = $("#groupName").val();
        getServer(val)

    }

    // 监听下拉框改变事件,修改输入框中的内容
    form.on("select(serverId)",function(data){
        let value=data.value
        let selectObj=dropData.filter(item=>{
            return item.id==value
        })
        $("#groupName").val(selectObj[0].ip);
    })


    projectNameInput = function(e){
        const val = $("#projectName").val();
        getProject(val)
    }
    let projectData
    function getProject(projectName) {
        $.ajax({
            type: "GET",//方法类型
            dataType: "json",//预期服务器返回的数据类型
            url: "/admProject/getAll?name="+projectName,//url
            success: function (result) {
                projectData = result
                $("#projectId").html("");
                var html = "";
                $("#projectId").html("<option value=\"\">请选择项目</option>");
                if (result != null) {
                    $.each(result, function (index, item) {
                        html += "<option  value='" + item.id + "'>" + item.projectName + "</option>";
                    })
                }
                $("#projectId").append(html);
                form.render('select');
                if (projectName != null && projectName !=''){
                    $(".projectId").find(".layui-form-select").addClass("layui-form-selected")
                }
            },
            error: function () {
                alert("异常！");
            }
        });
    }
    // 监听下拉框改变事件,修改输入框中的内容
    form.on("select(projectId)",function(data){
        let value=data.value
        let selectObj=projectData.filter(item=>{
            return item.id==value
        })
        $("#projectName").val(selectObj[0].projectName);
    })

    namespaceNameInput = function(e){
        const val = $("#namespaceName").val();
        getNamespace(val)
    }
    let namespaceData
    function getNamespace(name) {
        $.ajax({
            type: "GET",//方法类型
            dataType: "json",//预期服务器返回的数据类型
            url: "/admNamespace/getAll?name="+name,//url
            success: function (result) {
                namespaceData = result
                $("#namespaceId").html("");
                var html = "";
                $("#namespaceId").html("<option value=\"\">请选择命名空间</option>");
                if (result != null) {
                    $.each(result, function (index, item) {
                        html += "<option  value='" + item.id + "'>" + item.name + "</option>";
                    })
                }
                $("#namespaceId").append(html);
                form.render('select');
                if (name != null && name !=''){
                    $(".namespaceId").find(".layui-form-select").addClass("layui-form-selected")
                }
            },
            error: function () {
                alert("异常！");
            }
        });
    }
    // 监听下拉框改变事件,修改输入框中的内容
    form.on("select(namespaceId)",function(data){
        let value=data.value
        let selectObj=namespaceData.filter(item=>{
            return item.id==value
        })
        $("#namespaceName").val(selectObj[0].name);
    })

});